#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>

#include "tcp.h"

static struct rowcol rc;

static struct sockaddr_in servaddr;
static struct sockaddr_in cliaddr;

static socklen_t cliaddr_len;

static int listenfd;
static int connfd;
static int sockfd;

void init_tcp_server(int argc, char **argv)
{
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(SERV_PORT);

	listenfd = socket(AF_INET, SOCK_STREAM, 0);
	bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

	listen(listenfd, 1);

	cliaddr_len = sizeof(cliaddr);
	connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &cliaddr_len);
}

void init_tcp_client(int argc, char **argv)
{
	char *server;

	if (argc == 1)
		server = "127.0.0.1";
	else
		server = argv[1];

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	inet_pton(AF_INET, server, &servaddr.sin_addr);
	servaddr.sin_port = htons(SERV_PORT);

	sockfd = socket(AF_INET, SOCK_STREAM, 0);

	connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
}

int get_server_fd()
{
	return connfd;
}

int get_client_fd()
{
	return sockfd;
}

void send_to(int fd, int r, int c)
{
	rc.row = r;
	rc.col = c;

	write(fd, &rc, sizeof(rc));
}

void receive_from(int fd, int *r, int *c)
{
	read(fd, &rc, sizeof(rc));
	*r = rc.row;
	*c = rc.col;
}
